package org.hyl.javabase.socket;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class fserver {
	public static final int PORT = 12345;// �����Ķ˿ں�
	public static void main(String[] args) {
		System.out.println("����������...\n");
		try {
			ServerSocket serverSocket = new ServerSocket(PORT);
			Socket client = serverSocket.accept();
			new fHandlerThread(client);
		} catch (Exception e) {
			System.out.println("�������쳣: " + e.getMessage());
		}
	}
}

class fHandlerThread implements Runnable {
	private Socket socket;
	public fHandlerThread(Socket client) {
		socket = client;
		new Thread(this).start();
	}
	String path = System.getProperty("user.dir") + "/src/javabase/p201707017/receive1.bak";
	FileOutputStream fs=null;
	public void run() {
		try {
			DataInputStream input = new DataInputStream(socket.getInputStream());
			byte[] buf = new byte[1000];
			int i=0;
			int n=0;
			System.out.println("��ʼ���ա���");
			fs = new FileOutputStream(path);		
			while ((i = input.read(buf))!=-1)// ����Ҫע��Ϳͻ����������д������Ӧ,�������
			{
				fs.write(buf,0,i);
				System.out.println("len="+i+" buf"+buf.length);
				n+=i;
			}
			System.out.println("д����ɡ���"+n);
			fs.flush();
			fs.close();
			input.close();
		} catch (Exception e) {
			System.out.println("�������쳣: " + e.getMessage());
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (Exception e) {
					socket = null;
					System.out.println("����� finally �쳣:" + e.getMessage());
				}
			}
			if (fs != null) {
				try {
					fs.close();
				} catch (Exception e) {
					fs = null;				
				}
			}
			
		}
	}
}
